package cn.school.controller.logistics;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.TeachingMaterialCollect;
import cn.school.logistics.entity.Assets;
import cn.school.logistics.entity.AssetsStoreDetils;
import cn.school.logistics.service.AssetsService;
import cn.school.logistics.service.AssetsStoreDetilsService;
import cn.school.sys.entity.SysUser;
import cn.school.sys.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: AssetsController
 * @author: fangjin.tao
 * @date: 2022/12/10
 **/
@RestController
@Api(tags = "AssetsCategoryController => 资产管理")
@RequestMapping("/logistics/assets")
public class AssetsController {
	@Autowired
	private AssetsService assetsService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private AssetsStoreDetilsService assetsStoreDetilsService;
	
	@ApiOperation("【资产】获取列表")
	@GetMapping("/list")
	public CommonResult<CommonPage<Assets>> list(@RequestParam Map<String, Object> params) {
		int pageNum = Integer.parseInt((String) params.get("pageNum"));
		int pageSize = Integer.parseInt((String) params.get("pageSize"));
		String asseType = (String) params.get("asseType");
		String asseCode = (String) params.get("asseCode");
		String asseName = (String) params.get("asseName");
		String beginTime = (String) params.get("beginTime"); // 买入时间 - 左区间
		String endTime = (String) params.get("endTime");// 买入时间 - 右区间
		String assePersonName = (String) params.get("assePersonName");
		String asseStatus = (String) params.get("asseStatus");
		
		
		Page<Assets> page = new Page<>();
		page.setSize(pageSize);
		page.setCurrent(pageNum);
		
		LambdaQueryWrapper<Assets> queryWrapper = new LambdaQueryWrapper<>();
		if (StrUtil.isNotEmpty(asseType)) {
			queryWrapper.eq(Assets::getAsseType, asseType);
		}
		if (StrUtil.isNotEmpty(asseCode)) {
			queryWrapper.eq(Assets::getAsseCode, asseCode);
		}
		if (StrUtil.isNotEmpty(asseName)) {
			queryWrapper.like(Assets::getAsseName, asseName);
		}
		if (StrUtil.isNotEmpty(beginTime)) {
			queryWrapper.ge(Assets::getAsseBuyTime, DateUtil.parse(beginTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(endTime)) {
			queryWrapper.le(Assets::getAsseBuyTime, DateUtil.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		if (StrUtil.isNotEmpty(assePersonName)) {
			queryWrapper.like(Assets::getAssePersonName, assePersonName);
		}
		if (StrUtil.isNotEmpty(asseStatus)) {
			queryWrapper.eq(Assets::getAsseStatus, asseStatus);
		}

		queryWrapper.eq(Assets::getTenantId,SysUserUtils.getSysUser().getTenantId());
		queryWrapper.orderByDesc(Assets::getAsseBuyTime);
		IPage<Assets> iPage = this.assetsService.page(page, queryWrapper);
		
		return CommonResult.success(CommonPage.restPage(iPage));
	}
	
	@ApiOperation("【资产】获取详情")
	@GetMapping("/info/{id}")
	public CommonResult<Assets> getInfoById(@PathVariable Long id) {
		Assets assets = this.assetsService.getById(id);
		if (assets == null) {
			throw new ApiException("领用记录不存在，请刷新页面");
		}
		return CommonResult.success(assets);
	}
	
	@ApiOperation("【资产】添加或更新")
	@PostMapping("/addOrUpdate")
	@Transactional
	public CommonResult<Assets> add(@RequestBody Assets assets) {
		boolean isAddSuccess = false;
		LambdaQueryWrapper<Assets> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Assets::getAsseCode, assets.getAsseCode());
		if (assets.getId() == null) {
			int count = this.assetsService.count(queryWrapper);
			if (count != 0) {
				throw new ApiException("资产编已存在，请修改后，再重新提交");
			}
			if (StrUtil.isNotEmpty(SysUserUtils.getSysUser().getSysuName())) {
				assets.setAssePersonName(SysUserUtils.getSysUser().getSysuName());
			} else {
				assets.setAssePersonName(SysUserUtils.getSysUser().getUsername());
			}
			assets.setCreateTime(Calendar.getInstance().getTime());
			assets.setModifyTime(Calendar.getInstance().getTime());
			assets.setCreateBy(SysUserUtils.getSysUser().getId());
			
			isAddSuccess = this.assetsService.save(assets);
			
			
			// 何存sku明细
			AssetsStoreDetils sku = new AssetsStoreDetils();
			sku.setAsseCode(assets.getAsseCode());
			sku.setAsseName(assets.getAsseName());
			sku.setCreateBy(SysUserUtils.getSysUser().getId());
			sku.setCreateTime(Calendar.getInstance().getTime());
			sku.setModifyTime(Calendar.getInstance().getTime());
			sku.setAsseId(assets.getId());
			sku.setAsdeType("1"); // 入库
			sku.setAsdeProcNotCount(0);
			sku.setAsdeCount(assets.getAsseCount());
			sku.setAsdeProcAfterCount(assets.getAsseCount());
			boolean isSkuSuccess = this.assetsStoreDetilsService.save(sku);
			
			
		} else {
			queryWrapper.ne(Assets::getId, assets.getId());
			int count = this.assetsService.count(queryWrapper);
			if (count != 0) {
				throw new ApiException("资产编已存在，请修改后，再重新提交");
			}
			assets.setAsseCount(null);
			assets.setModifyTime(Calendar.getInstance().getTime());
			assets.setModifyBy(SysUserUtils.getSysUser().getId());
			isAddSuccess = this.assetsService.updateById(assets);
		}
		if (isAddSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("【资产】删除")
	@DeleteMapping("/deleteByIds/{ids}")
	public CommonResult<TeachingMaterialCollect> delete(@PathVariable Long[] ids) {
		List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
		boolean isDeleteSuccess = this.assetsService.removeByIds(idList);
		if (isDeleteSuccess) {
			return CommonResult.success();
		} else {
			return CommonResult.failed();
		}
	}
	
	@ApiOperation("【资产】查询用户")
	@GetMapping("/user/list")
	public CommonResult<List<SysUser>> buildList(@RequestParam Map<String, Object> params) {
		String userName = (String) params.get("userName");
		
		LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
		if (StrUtil.isNotEmpty(userName)) {
			queryWrapper.like(SysUser::getUsername, userName);
		}
		List<SysUser> list = this.sysUserService.list(queryWrapper);
		return CommonResult.success(list);
	}
}
